# -*- coding: utf-8 -*-
# @Time    : 2020/10/18 16:01
# @Author  : liupengfei
# @File    : serializers.py
import json
import random, re, string

from django_redis import get_redis_connection
from rest_framework import serializers
from django.contrib.auth import get_user_model
from rest_framework_jwt.serializers import VerificationBaseSerializer
from rest_framework_jwt.settings import api_settings
from rest_framework.exceptions import ValidationError
from utils.wechat_applet import WeChatApplet
from .models import Member, MemberRecord

User = get_user_model()
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class MemberMobileSignSerializer(serializers.Serializer):

    def validate(self, attrs):
        # userinfo = json.loads(self.initial_data.get('userInfo'))
        mobile = self.initial_data.get('mobile')
        # vcode = self.initial_data.get('vcode')
        # 小程序的用户信息
        # if not mobile or not vcode:
        #     raise ValidationError('参数无效')

        # 验证码验证,从redis中取出来
        # conn = get_redis_connection()
        # redis_code = conn.get(mobile)

        # if not redis_code:
        #     raise ValidationError('短信验证码已失效')
        # if vcode != redis_code.decode('utf-8'):
        #     raise ValidationError('短信验证码错误')

        # 验证通过
        user = User.objects.filter(username=mobile).first()
        if not user:
            """注册"""
            userinfo = {'nickName': 'QiaoFinn_lpf', 'gender': 1, 'language': 'zh_CN', 'city': '烟台', 'province': '山东',
                        'country': '中国',
                        'avatarUrl': 'https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJkKNKezgVwHibQboGP19bTuyPKM4ukmx3jJU0FjNs1GLblx4VXpt9ickgyhMia8E3vnV5PvlFkKxxJg/132'}
            user = User.objects.create_user(username=mobile, nickname=userinfo['nickName'])
            # {'nickName': 'QiaoFinn_lpf', 'gender': 1, 'language': 'zh_CN', 'city': '烟台', 'province': '山东', 'country': '中国', 'avatarUrl': 'https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJkKNKezgVwHibQboGP19bTuyPKM4ukmx3jJU0FjNs1GLblx4VXpt9ic
            # kgyhMia8E3vnV5PvlFkKxxJg/132'}
            Member.objects.create(user=user, face_url=userinfo['avatarUrl'], gender=userinfo['gender'],
                                  province=userinfo['province'], city=userinfo['city'])
            # MemberRecord.objects.create(content_object=user, user=user, operate=MemberRecord.SIGN, describe='第一次注册')

        payload = jwt_payload_handler(user)

        return {
            'token': jwt_encode_handler(payload),
            'username': user.nickname
        }


class WeChatCode2sessionSerializer(serializers.Serializer):
    def validate(self, attrs):
        # print(self.initial_data)
        code = self.initial_data.get('code')
        if not code:
            raise serializers.ValidationError('参数无效')
        res = WeChatApplet().get_openid_by_code(code)
        # {'session_key': 'sr0ZsoffP8ZE5+ZfEFKBLw==', 'expires_in': 7200, 'openid': 'oNAnw0CTK4o-zWdkJ1_Hp-j93aXA'}
        openid = res.get('openid')
        # openid = ''.join(random.sample(string.ascii_letters + string.digits, 10))
        member = Member.objects.filter(wechat_openid=openid).first()

        # print(member) 7200 /60   120/60 2
        if member:
            user = member.user
            # print('------------------------------------------', res.get('session_key'))
            member.session_key = res.get('session_key')
            member.save()
        else:
            user = User.objects.create_user(username=openid)
            member = Member.objects.create(user=user, wechat_openid=openid, session_key=res.get('session_key'))

        payload = jwt_payload_handler(user)

        return {
            'token': jwt_encode_handler(payload),
            'userInfo': MemberInfoSerializer(member).data,
        }


class WeChatBindUserInfoSerializer(serializers.Serializer):
    '''微信小程序授权绑定'''

    def validate(self, attrs):
        iv = self.initial_data.get('iv')
        encryptedData = self.initial_data.get('encryptedData')
        if not iv or not encryptedData:
            raise serializers.ValidationError('参数无效')
        user = self.context['request'].user
        decrypted = WeChatApplet().decrypt(encryptedData, iv, user.member.session_key)
        # {'phoneNumber': '17616153358', 'purePhoneNumber': '17616153358', 'countryCode': '86', 'watermark': {'timestamp': 1603327582, 'appid': 'wx5adceddecc753b75'}}
        user.username = decrypted['phoneNumber']
        user.save()
        member = user.member
        member.phoneNumber = decrypted['phoneNumber']
        member.save()
        payload = jwt_payload_handler(user)
        return {
            'token': jwt_encode_handler(payload),
            'userInfo': MemberInfoSerializer(member).data,
        }


class MemberJwtSerializer(serializers.ModelSerializer):
    '''刷新token返回的数据'''

    class Meta:
        model = Member
        fields = '__all__'


class MemberInfoSerializer(serializers.ModelSerializer):
    nickname = serializers.CharField(source='user.nickname', read_only=True)

    class Meta:
        model = Member
        fields = ('id', 'face_url', 'gender', 'nickname', 'phoneNumber')
